package com.whk.controller;

import com.whk.pojo.Emp;
import com.whk.pojo.Result;
import com.whk.service.EmpService;
import com.whk.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 处理登录请求
 */
@RestController
@Slf4j
public class LoginController {
    //注入service实现类
    @Autowired
    EmpService empService;

    /**
     * 登录请求
     * @param emp
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Emp emp){

        Emp emp1 = empService.login(emp);//调用service接口
        log.info("查询用户{}",emp);

        //判断用户是否是合法用户
        if (emp1 != null){
            //创建Map对象，用于存储用户生成JWT的信息
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", emp1.getId());
            claims.put("name", emp1.getName());
            claims.put("username", emp1.getUsername());
            //生成令牌，并下发令牌
            String jwt = JwtUtils.generateJwt(claims);
            return Result.success(jwt);
        }

        return Result.error("用户名或密码错误");
    }
}
